package com.katesoft.scale4j.agent.args;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;

import java.io.IOException;

import static com.katesoft.scale4j.common.io.FileUtility.LINE_SEPARATOR;
import static com.katesoft.scale4j.log.LogFactory.getLogger;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.EMPTY;

/**
 * Utility class for parsing application arguments.
 *
 * @author kate2007
 */
public class AgentArgsParser
{
    public static AgentOptions parseAndValidateOptions(String[] args)
    {
        AgentOptions options = new AgentOptions();
        CmdLineParser parser = new CmdLineParser(options);
        parser.setUsageWidth(150);
        try {
            parser.parseArgument(args);
            // validate
            options.appConfigurationLocation();
            options.log4jConfigurationLocation();
            //
            getLogger(AgentArgsParser.class)
                .debug("parsed args %s(%s%s)", ReflectionToStringBuilder.reflectionToString(options, ToStringStyle.MULTI_LINE_STYLE),
                       (options.appConfigurationLocation() == null ? EMPTY :
                           format("%s app_config_resource   :=> %s", LINE_SEPARATOR, options.appConfigurationLocation().getDescription())),
                       (options.log4jConfigurationLocation() == null ? EMPTY :
                           format("%s log4j_config_resource :=> %s", LINE_SEPARATOR, options.log4jConfigurationLocation().getDescription())));
        }
        catch (CmdLineException e) {
            System.err.println(e.getMessage());
            // print the list of available options
            parser.printUsage(System.err);
            System.err.println();
            throw new IllegalArgumentException(e);
        }
        catch (IOException e) {
            getLogger(AgentArgsParser.class).error(e);
            throw new IllegalArgumentException(e);
        }
        return options;
    }

    private AgentArgsParser() {}
}
